from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.schemas import ConversationCreate, ConversationOut
from app.models import Conversation
from app.core.deps import get_db

router = APIRouter(prefix="/conversations", tags=["Conversations"])

@router.post("/", response_model=ConversationOut)
def create_conversation(convo: ConversationCreate, db: Session = Depends(get_db)):
    db_convo = Conversation(**convo.dict())
    db.add(db_convo)
    db.commit()
    db.refresh(db_convo)
    return db_convo

@router.get("/{convo_id}", response_model=ConversationOut)
def get_conversation(convo_id: int, db: Session = Depends(get_db)):
    convo = db.query(Conversation).filter(Conversation.id == convo_id).first()
    if not convo:
        raise HTTPException(status_code=404, detail="Conversation not found")
    return convo

@router.get("/", response_model=List[ConversationOut])
def list_conversations(
    skip: int = 0,
    limit: int = Query(20, le=100),
    user_id: Optional[str] = None,
    role: Optional[str] = None,
    db: Session = Depends(get_db),
):
    query = db.query(Conversation)
    if user_id:
        query = query.filter(Conversation.user_id == user_id)
    if role:
        query = query.filter(Conversation.role == role)
    return query.order_by(Conversation.timestamp.desc()).offset(skip).limit(limit).all()

@router.delete("/{convo_id}", response_model=dict)
def delete_conversation(convo_id: int, db: Session = Depends(get_db)):
    convo = db.query(Conversation).filter(Conversation.id == convo_id).first()
    if not convo:
        raise HTTPException(status_code=404, detail="Conversation not found")
    db.delete(convo)
    db.commit()
    return {"success": True, "deleted_id": convo_id} 